//
//  WQComposeController.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/16.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit
import SVProgressHUD

class WQComposeController: UIViewController {


    
    private lazy var picturePickerVC = WQPicturePickerController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        WQNotificationCenter.addObserver(self, selector: "keyboardFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        setupUI()
    }
    
    deinit{
        WQNotificationCenter.removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if picturePickerVC.collectionView!.bounds.height > 0 {
            return
        }
        textInputView.becomeFirstResponder()
    }


    
    override func loadView() {
        super.loadView()
        ///  ************************ 必须成为父控制器的子控制器才能进行事件传递 ***********************************
        self.addChildViewController(picturePickerVC)
        ///  ************************ 必须成为父控制器的子控制器才能进行事件传递 ***********************************
        self.view.insertSubview(picturePickerVC.collectionView!, belowSubview: self.keyboardBar)
        picturePickerVC.collectionView!.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom)
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.height.equalTo(0)
        }

    }
    
    @objc private func dismiss() {
        print("返回")
        textInputView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func send() {
        let statusContent = textInputView.textStr
        WQNetTool.shareTool.sendStatus(WQAccountViewModel.sharedAccount.account!, statusContent: statusContent) { (success, failure) -> () in
            if (failure != nil) {
                SVProgressHUD.showSuccessWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
            
        }
        textInputView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
        
//        WQNetTool.shareTool.
    }
    
    
    //懒加载控件
    lazy var textInputView:UITextView = UITextView()
    lazy var placeHolderLabel: UILabel = UILabel(title: "站位文字", color: UIColor.lightGrayColor(), fontSize: 18)
    lazy var keyboardBar: WQKeyboardToolBar = WQKeyboardToolBar()
}




// MARK: - 搭建控制器UI界面
extension WQComposeController {
    
    private func setupUI() {
        
        // 0. 取消自动调整滚动视图间距
        automaticallyAdjustsScrollViewInsets = false
        setupNavigationItems()
        setupTitleView()
        setupInputView()
        setupKeyboardBar()
        
    }
    
    private func setupNavigationItems() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false

    }
    
    private func setupTitleView() {
        let titleView = UIView()
        navigationItem.titleView = titleView
        titleView.frame = CGRect(x: 0, y: 0, width: 200, height: 35)
        let titleLabel: UILabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 16)
        let nameLabel: UILabel = UILabel(title: "用户名", color: UIColor.lightGrayColor(), fontSize: 11)

        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.left.equalTo(titleView.snp_left)
            make.width.equalTo(titleView.snp_width)
            make.height.equalTo(20)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleLabel.snp_bottom)
            make.width.equalTo(titleView.snp_width)
            make.left.equalTo(titleView.snp_left)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        
    }
    private func setupInputView() {
        textInputView.font = UIFont.systemFontOfSize(18)
        textInputView.alwaysBounceVertical = true
        textInputView.keyboardDismissMode = .OnDrag
        textInputView.delegate = self
        view.addSubview(textInputView)
        
        placeHolderLabel.backgroundColor = randomColor
        textInputView.addSubview(placeHolderLabel)
        
        textInputView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.top.equalTo(self.view.snp_top).offset(64)
            make.bottom.equalTo(self.view.snp_bottom)
        }
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.textInputView.snp_left).offset(5)
            make.right.equalTo(self.textInputView.snp_right)
            make.top.equalTo(self.textInputView.snp_top).offset(8)
        }
    }
    
    private func setupKeyboardBar() {
        view.addSubview(keyboardBar)
        keyboardBar.delegate = self
        keyboardBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom)
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.height.equalTo(44)
        }
    }
}


// MARK: - UITextViewDelegate监听方法
extension WQComposeController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
    }
}

var isChangeEmotionKeboard = false
// MARK: - 通知监听方法
extension WQComposeController {
    
    @objc private func keyboardFrameChange(noti: NSNotification) {
        if isChangeEmotionKeboard {
            return
        }
        //获取键盘的最终位置 UIKeyboardFrameEndUserInfoKey
        let rect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //获取动画偏移量
        let offset = rect.origin.y - UIScreen.mainScreen().bounds.size.height
    
        //获取动画时长    UIKeyboardAnimationDurationUserInfoKey
//        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //获取动画曲线    UIKeyboardAnimationCurveUserInfoKey
//        let curve = (noti.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        keyboardBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom).offset(offset)
        }

        UIView.animateWithDuration(0.1) { () -> Void in
//            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
}

// MARK: - WQKeyboardToolBarDelegate代理方法实现
extension WQComposeController: WQKeyboardToolBarDelegate {
    
    func keyboardToolBarButtonDidClick(toolBarButton: WQKeyboardButton) {
        
        let finished:(selectedEmotion: WQEmotion) -> () = {[weak self] (selectedEmotion: WQEmotion) -> () in
            self?.textInputView.insertSelectedEmotion(selectedEmotion)
            
        }
        switch toolBarButton.toolBarButtonType {
        case WQKeyboardButtonType.cameraButton: print("cameraButton")
        case WQKeyboardButtonType.pictureButton: pickerPicture()
        case WQKeyboardButtonType.mentionButton: print("mentionButton")

        case WQKeyboardButtonType.emotionButton:
            {   //切换键盘
                isChangeEmotionKeboard = true
                textInputView.resignFirstResponder()
                self.textInputView.inputView = (self.textInputView.inputView == nil) ? WQKeyboardView(finishedCallBack: finished) : nil
                isChangeEmotionKeboard = false
                self.textInputView.becomeFirstResponder()
            }()
            
        }
    }
    
    func pickerPicture() {
        //对照片进行选择
        textInputView.resignFirstResponder()
        
        textInputView.snp_remakeConstraints { (make) -> Void in
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.top.equalTo(self.view.snp_top).offset(64)
            make.bottom.equalTo(picturePickerVC.collectionView!.snp_top)
        }
        
        picturePickerVC.collectionView!.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(self.view.bounds.height * 0.7)
        }
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
}

